//
//  FiltersTableViewController.m
//  StanfordUp
//
//  Created by Gongmyung on 8/16/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FiltersTableViewController.h"
#import "StanfordEventsAppDelegate.h"


@implementation FiltersTableViewController


#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style andTags:(NSMutableArray*)initialTags withContext:(NSManagedObjectContext*)moj {
    if ((self = [super initWithStyle:style])) {
        filters = initialTags;
        [filters retain];
        
        selectedTags = [[NSMutableDictionary alloc] init];
        for (Tag *tag in filters ) {
            [selectedTags setObject:[NSNumber numberWithInt:1] forKey:tag.name];
        }
        
        managedObjectContext = moj;
        [managedObjectContext retain];
    }
    return self;
}

- (void)addFilterToList:(Tag*)toAdd {
    if( ![filters containsObject:toAdd] ) {
        [filters insertObject:toAdd atIndex:0];
        [self.tableView reloadData];
        //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        //[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Filters";
 
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addFilter)];
    self.navigationItem.rightBarButtonItem = addButton;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)addFilter {
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Add a Tag" message:@"canceling..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
    [myTextField setBackgroundColor:[UIColor whiteColor]];
    [myAlertView addSubview:myTextField];
    //CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 130.0);
    //[myAlertView setTransform:myTransform];
    [myAlertView show];
    [myAlertView release];
}

//alert view delegate methods
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if( buttonIndex == 1 && myTextField.text.length > 0 ) {
        Tag *tag = (Tag *)[NSEntityDescription insertNewObjectForEntityForName:@"Tag" inManagedObjectContext:managedObjectContext];
        
        tag.name = myTextField.text;
        [filters addObject:tag];
        
        NSError *error;
        if (![managedObjectContext save:&error]) {
            NSLog(@"failed to save created tag");
        }
        
        [self.tableView reloadData];
    }
    [myTextField release];
}

//helper methods
- (void)applyFilter:(Tag*)tag {
    NSError *error;
    tag.selected = [NSNumber numberWithInt:1];
    [managedObjectContext save:&error];
    
    StanfordEventsAppDelegate *appDelegate = (StanfordEventsAppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.mapViewController.needsUpdate = YES;
    appDelegate.eventsListViewController.needsUpdate = YES;
    appDelegate.localEventsListViewController.needsUpdate = YES;
}
- (void)unapplyFilter:(Tag*)tag {
    NSError *error;
    tag.selected = [NSNumber numberWithInt:0];
    [managedObjectContext save:&error];
    
    StanfordEventsAppDelegate *appDelegate = (StanfordEventsAppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.mapViewController.needsUpdate = YES;
    appDelegate.eventsListViewController.needsUpdate = YES;
    appDelegate.localEventsListViewController.needsUpdate = YES;
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return filters.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    Tag *tag = (Tag*)[filters objectAtIndex:indexPath.row]; 
    
    cell.textLabel.text = [tag name];
    
    if ( [(NSNumber*)[selectedTags objectForKey:tag.name] intValue] == 1 ) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self applyFilter:tag];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [self unapplyFilter:tag];
    }
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	//add checkmark
    Tag *tag = [filters objectAtIndex:indexPath.row];
    if ( [(NSNumber*)[selectedTags objectForKey:tag.name] intValue] == 1 ) {
        [selectedTags setObject:[NSNumber numberWithInt:0] forKey:tag.name];
    }
    else {
        [selectedTags setObject:[NSNumber numberWithInt:1] forKey:tag.name];
    }
    [tableView reloadData];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [filters release];
    [selectedTags release];
    [managedObjectContext release];
    [super dealloc];
}


@end

